//
//  ShareViewController.swift
//  ReceivePDF
//
//  Created by Jarvis on 08/05/2017.
//  Copyright © 2017 Jarvis. All rights reserved.
//

import UIKit
import Social
import MobileCoreServices
import Localize_Swift


class ShareViewController: UIViewController {
    
    @IBOutlet weak var alertTitleButton: UIButton!
    @IBOutlet weak var leftItemButton: UIButton!
    @IBOutlet weak var rightItemButton: UIButton!
    
    @IBOutlet weak var layoutView: UIView!
    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var iconView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    
    @IBOutlet weak var resultLayoutView: UIView!
    @IBOutlet weak var resultContentView: UIView!
    @IBOutlet weak var resultContentLabel: UILabel!
    @IBOutlet weak var resultTitleButton: UIButton!
    @IBOutlet weak var okButton: UIButton!
    
    var fileURL: URL?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 配置友盟统计
        configTalkingData()
        
        loadItem(completeHandler: {[weak self] (success, message) in
            
            if success {
                DispatchQueue.main.async {
                    self?.prepareUI()
                }
            }else {
                DispatchQueue.main.async {
                    print("\(message!)")
                    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                        self?.dismissExtension()
                    }
                }
            }
        })
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
//        Tracker.pageBegin(self.className)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
//        Tracker.pageEnd(self.className)
    }
    
    func prepareUI() {
        alertTitleButton.setTitle("Portal".localized(), for: .normal)
        leftItemButton.setTitle("Cancel".localized(), for: .normal)
        rightItemButton.setTitle("Save".localized(), for: .normal)
        
        resultTitleButton.setTitle("File Saved".localized(), for: .normal)
        resultContentLabel.text = "Review this document in the PDF2IMG app.".localized()
        
        
        layoutView.isHidden = false
        
        layoutView.layer.cornerRadius = 6;
        contentView.layer.cornerRadius = 6;
        
        resultLayoutView.layer.cornerRadius = 6;
        resultContentView.layer.cornerRadius = 6;
        resultTitleButton.layer.cornerRadius = 6;
        okButton.layer.cornerRadius = 6;
        
        titleLabel.text = fileURL?.lastPathComponent
    }
    
    
    //MARK: events
    @IBAction func rightItemPressed(_ sender: UIButton) {
//        Tracker.fileSave()
        
        saveFile()
    }
    
    @IBAction func leftItemPressed(_ sender: UIButton) {
//        Tracker.fileCancel()
        
        dismissExtension()
    }
    
    
    @IBAction func noButtonPressed(_ sender: UIButton) {
        self.dismissExtension()
    }
    
    @IBAction func okButtonPressed(_ sender: UIButton) {
        //        let hostURL = URL(string: "pdf2img://")
        //        self.extensionContext?.open(hostURL!, completionHandler: nil)
        self.dismissExtension()
        
//        Tracker.resultOK()
    }
    
    
    
    func loadItem(completeHandler: ((Bool, String?) -> Void)?) {
        
        let inputItem = self.extensionContext?.inputItems.first as! NSExtensionItem
        let itemProvider = inputItem.attachments?.first as! NSItemProvider
        
        let typePDF = String(kUTTypePDF)
        
        if itemProvider.hasItemConformingToTypeIdentifier(typePDF) {
            itemProvider.loadItem(forTypeIdentifier: typePDF, options: nil, completionHandler: {[weak self] (item, error) in
                if error == nil {
                    print("加载数据: \(String(describing: item))")
                    if let fileURL = item as? URL {
                        print("文件路径: \(String(describing: fileURL))")
                        
                        self?.fileURL = fileURL
                        
                        if let handler = completeHandler {
                            handler(true, nil)
                        }
                        
//                        Tracker.fileLoadingSuccess()
                    }
                }else {
                    print("数据错误：\(error)");
                    if let handler = completeHandler {
                        handler(false, "File data is incorrect.")
                    }
                }
            })
        }else {
            print("不支持的文件格式。");
            if let handler = completeHandler {
                handler(false, "Unsupported file type.")
            }
            
//            Tracker.fileShareError(reason: eventid_share_error_type)
        }
    }
    
    func saveFile() {
        
        if fileURL != nil {
            if (fileURL?.pathExtension == ".pdf") {
                print("文件格式错误");
//                Tracker.fileShareError(reason: eventid_share_error_type)
                return;
            }
            
            let uuid = UUID().uuidString
            let newFileName = String(format: "%@.pdf", uuid);
            
            let fileManager = FileManager.default
            
            let groupURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.pdf2png")
            let newFileURL = groupURL!.appendingPathComponent(newFileName)
            
            print("groupURL: \(newFileURL.absoluteString)")
            
            do {
                try fileManager.copyItem(at: fileURL!, to: newFileURL)
                
                let newItem = ["fileName": fileURL?.lastPathComponent, "filePath": newFileURL.path, "createAt": String(format:"%lld", Date().timeIntervalSinceNow)] as! [String : String]
                
                var pdfItems = [[String : String]]()
                
                let userDefault = UserDefaults(suiteName: "group.pdf2png");
                
                if let items = userDefault?.value(forKey: "pdfItems") {
                    let newItems = items as? [[String : String]]
                    if (newItems?.count)! > 0 {
                        pdfItems.append(contentsOf: newItems!);
                    }
                }
                
                pdfItems.insert(newItem, at: 0);
                userDefault?.set(pdfItems, forKey: "pdfItems")
                userDefault?.synchronize()
                
                print("文件保存成功：\(newFileURL)")
//                Tracker.fileSaveSuccess()
                
                showLayoutView(isShow: false)
                showResultView(isShow: true)
                
            } catch let error2 as NSError {
                print("文件拷贝错误:\(error2)")
//                Tracker.fileShareError(reason: eventid_share_error_save)
            }
            
        }
    }
    
    
    //MARK: others
    func showLayoutView(isShow: Bool) {
        layoutView.isHidden = !isShow
    }
    
    
    func showResultView(isShow: Bool) {
        resultLayoutView.isHidden = !isShow
    }
    
    
    func dismissExtension() {
        self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
    }

    func configTalkingData() {
        // App ID: 在 App Analytics 创建应用后，进入数据报表页中，在“系统设置”-“编辑应用”页面里查看App ID。
        // 渠道 ID: 是渠道标识符，可通过不同渠道单独追踪数据。
//        TalkingData.sessionStarted(td_appkey, withChannelId: channel_id);
        //other code
    }
    
}

